#!/usr/local/lua52/bin/lua

local cqueues = require("cqueues")
local socket = require("cqueues.socket")
local host, port = ...

host = host or "google.com"
port = tonumber(port or 80)

local http = socket.connect(host, port)

if port == 443 then
	http:starttls()
end

local cq = cqueues.new()

cq:wrap(function()
	http:write("GET / HTTP/1.0\n")
	http:write(string.format("Host: %s:%d\n\n", host, port))

	local status = http:read()
	print("!", status)

	for ln in http:lines"*h" do
		print("|", ln)
	end

	local empty = http:read"*L"

	if empty and empty:match"^[^\r\n]" then
		http:unget(empty)
	end

	print"~"

	for ln in http:lines"*L" do
		io.stdout:write(ln)
	end

	http:close()
end)

while not cq:empty() do
	local ok, err = cq:step()

	if not ok then
		error("cqueue: " .. err)
	end
end

